
package com.handong.handserialprogram.module.createmission.searchring;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.handong.handserialprogram.constants.HttpConstant;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.entities.PersonEntity;
import com.handong.handserialprogram.model.status.RingResponse;
import com.handong.handserialprogram.module.base.BasePresenter;
import com.handong.handserialprogram.module.base.BaseView;
import com.handong.handserialprogram.module.createmission.CreateMissionActivity;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.AsyncHttpUtil;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.FootRingNewUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.utils.SystemUtil;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 快捷模式SearchRingFragment：选择可用脚环。
 * Created by userKey on 2017/8/2.
 */
public class SearchRingPresenter extends BasePresenter<SearchRingFragment> {

    private static final String TAG = SearchRingPresenter.class.getSimpleName();
    //public SerialPortUtil mSerialPortUtil;
    //private Vector<FootRingNewEntity> mRingList;
    private Vector<FootRingNewEntity> logoutFR;
    private boolean isLogoutAll=false;
    private boolean mIsCloseSerialPort = true;

    public SearchRingPresenter(BaseView view) {
        super(view);
        logoutFR=new Vector<>();
    }

//    protected void setRingList(Vector<FootRingNewEntity> list)
//    {
//        if (mSerialPortUtil!=null)
//        {
//            mSerialPortUtil.setRingList(list);
//        }
//    }



    protected void closeSerialPort()
    {
        CreateMissionActivity activity = (CreateMissionActivity) mView.getActivity();
        if (activity.mSerialPortUtil!=null)
        {
            activity.mSerialPortUtil.closeSerialPort();
        }
    }
    protected void scanAroundFootRing() {
        CreateMissionActivity activity = (CreateMissionActivity) mView.getActivity();
        EventBusUtil.register(this);
        activity.mSerialPortUtil = SerialPortUtil.getInstance(mView.getContext());
        activity.mSerialPortUtil.openSerialPortToReadData();
        activity.mSerialPortUtil.updateWorking(false);
    }

    public void activateFootRing(String id) {
        CreateMissionActivity activity = (CreateMissionActivity) mView.getActivity();
        FootRingNewEntity entity= FootRingNewUtil.findFootRingById(activity.getmRingList(),id);
        if (entity!=null&&entity.isNormalWork()) {
            AppUtil.showShortToast(mView.getContext(), "脚环已激活");
            return;
        }
        mView.showLoadDialog("脚环激活中...");
        activity.mSerialPortUtil.activateFootRing(id);
    }

    public void logoutFootRing(String id) {
        CreateMissionActivity activity = (CreateMissionActivity) mView.getActivity();
        this.mView.showLoadDialog("脚环休眠中...");
        activity.mSerialPortUtil.logoutFootRing(id);
    }
    public void logoutAllFootRing() {
        CreateMissionActivity activity = (CreateMissionActivity) mView.getActivity();
        if(!logoutFR.isEmpty()&&activity.mSerialPortUtil!=null){
            isLogoutAll=true;
            this.mView.showLoadDialog("正在休眠脚环...");
            activity.mSerialPortUtil.mSendRunnable.DelayTime=100;
            activity.mSerialPortUtil.mSendRunnable.isLoginOut=true;
        }
    }

    protected void forceExit(String id) {
        CreateMissionActivity activity = (CreateMissionActivity) mView.getActivity();
        FootRingNewEntity entity= FootRingNewUtil.findFootRingById(activity.getmRingList(),id);
        if(entity!=null){
            entity.setNormalWork(false);
        }
    }

    @Subscribe(priority = 98, threadMode = ThreadMode.MAIN)
    public void receiveFootRing(CopyOnWriteArrayList<FootRingNewEntity> list) {
        CreateMissionActivity activity = (CreateMissionActivity) mView.getActivity();
        //if (activity.getmRingList() == null) {
            activity.setmRingList(list);
        //}

        logoutFR.clear();
        for (FootRingNewEntity entity:activity.getmRingList()) {
            if(entity.isMyBingding()&&entity.isNormalWork()){
                logoutFR.add(entity);
            }
        }


        this.mView.showFootRingList(list);
    }

    @Subscribe(priority = 98, threadMode = ThreadMode.MAIN)
    public void receiveRingResponse(RingResponse response) {
        switch (response.getResponseCode()) {
            case RingResponse.ACTIVATE_ORDER:
                if (response.isSuccess()) {
                    mView.showLoadDialog("脚环正在连接GPS和网络...");
                } else {
                    mView.activateRingError(response.getRingID());
                }
                break;

            case RingResponse.INIT_2GNET_SUCCESS:
                if (response.isSuccess()) {
                    mView.activateRingSuccess();
                } else {
                    mView.activateRingError(response.getRingID());
                }
                break;

            case RingResponse.LOGOUT_ORDER:
//                if (response.isSuccess()) {
//                    if(!logoutFR.isEmpty()&&isLogoutAll){
//                        logoutFR.remove(FootRingNewUtil.findFootRingById(logoutFR,response.getRingID()));
//                        logoutAllFootRing();
//                        if(logoutFR.isEmpty()){
//                            isLogoutAll=false;
//                            mView.dismissLoadingDialog();
//                            mView.logoutSuccess(response.getRingID());
//                        }
//                        break;
//                    }else{
//                        isLogoutAll=false;
//                        mView.dismissLoadingDialog();
//                        mView.logoutSuccess(response.getRingID());
//                    }
//                } else {
//                    isLogoutAll=false;
//                    mView.dismissLoadingDialog();
//                    mView.logoutFail(response.getRingID());
//                }\
                if (response.isSuccess()) {
                    CreateMissionActivity activity = (CreateMissionActivity) mView.getActivity();
                    if (activity!=null&&activity.getmRingList() != null){
                        FootRingNewEntity loginOutFootRing=FootRingNewUtil.findFootRingById(activity.getmRingList(), response.getRingID());
                        if (loginOutFootRing!=null) {
                            for (PersonEntity personEntity : mView.mUploadTaskEntity.getCriminal()) {
                                if (loginOutFootRing.getCriminalId() != null && loginOutFootRing.getCriminalId().equals(personEntity.getId())) {
                                    personEntity.setSelected(false);
                                }
                            }
                            activity.getmRingList().remove(loginOutFootRing);
                        }
                    }
                }


                break;

            case RingResponse.SIM_ERROR:
                mView.simInitError(response.getRingID());
                break;
            default:
                return;
        }
    }

    /**
     * 创建任务
     */
    protected void createSimpleTask() {
                //showLoadDialog("正在创建任务...");

        RequestParams params = new RequestParams();
        params.put("visit", "CreateMiss");
        params.put("policePhone", SPUtil.getStringValue(SPUtil.PHONE_NAME));
        params.put("sys_companycode", SPUtil.getStringValue(SPUtil.LOGIN_CODE));

        String ids = "";
        CreateMissionActivity activity = (CreateMissionActivity) mView.getActivity();
        for (FootRingNewEntity item : activity.getmRingList()) {
            if (item.isMyBingding())
            {
                ids+=item.getRingID()+";"+(item.getCriminalId().equals("")?" ":item.getCriminalId())+",";
                //ids+=item.getRingID()+",";
            }
        }
        if (ids.contains(","))
        {
            ids=ids.substring(0, ids.length()-1);
        }
        mView.mUploadTaskEntity.seteId(ids);

        Gson gson = new Gson();
        String data = gson.toJson(mView.mUploadTaskEntity);
        params.put("data", data);

        JLog.d(TAG, data);

        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                JLog.d(TAG, throwable.toString());
                mView.createTaskFail("服务器无响应");
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d(TAG, s + SystemUtil.getDateDetailsString());
                if (TextUtils.isEmpty(s) || s.length() < 15) {
                    mView.createTaskFail("服务器响应失败");
                    return;
                }
                if (s.length() < 15) {
                    mView.createTaskFail("服务器响应失败");
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.getBoolean(HttpConstant.RESPONSE_SUCCESS)) {
                        String missID = jsonObject.getString("missId");
                        mView.createTaskSuccess(missID);


                    } else {
                        mView.createTaskFail(jsonObject.getString(HttpConstant.FAIL_REASON));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

//        RequestParams params = new RequestParams();
//        params.put("visit", "CreateMostSimpleMiss");
//        params.put("sys_companycode", SPUtil.getStringValue(SPUtil.LOGIN_CODE));
//        //params.put("startDate", SystemUtil.getDateString());
//        params.put("Pid", SPUtil.getStringValue(SPUtil.PHONE_NAME));
////        params.put("Rid", mRingList.get(0).getRingID());
//        //TODO 要修改一对多
//        String ids = "";
//        for (FootRingNewEntity item : mRingList) {
//            if (item.isMyBingding())
//            {
//                ids+=item.getRingID()+",";
//            }
//        }
//        params.put("Rid", ids);
//
//        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
//            @Override
//            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
//                JLog.d(TAG, throwable.toString());
//                mView.createTaskFail("服务器无响应");
//                //mView.createTaskSuccess();
//            }
//
//            @Override
//            public void onSuccess(int i, Header[] headers, String s) {
//                JLog.d(TAG, s);
//                if (s.isEmpty() || s.length() < 15) {
//                    return;
//                }
//                try {
//                    JSONObject jsonObject = new JSONObject(s);
//                    if (jsonObject.getBoolean(HttpConstant.RESPONSE_SUCCESS)) {
//                        mIsCloseSerialPort = false;
//                        mView.createTaskSuccess(jsonObject.getString(HttpConstant.RESPONSE_ID));
//                    } else {
//                        mView.createTaskFail(jsonObject.getString(HttpConstant.FAIL_REASON));
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                    mView.createTaskFail("服务器无响应");
//                }
//            }
//        });
    }


    protected boolean isCanExit() {
        CreateMissionActivity activity = (CreateMissionActivity) mView.getActivity();
        if (activity.getmRingList() != null && !activity.getmRingList().isEmpty()) {
            if(logoutFR.size()>0){
                mView.showExitAllDialog();
                return false;
            }
            /*StringBuffer buffer=new StringBuffer();
            for (FootRingNewEntity footRingEntity:mRingList) {
                if (footRingEntity.isNormalWork()) {
                    buffer.append(footRingEntity.getRingID()+";");
                }
            }
            if(!TextUtils.isEmpty(buffer.toString())){
                String st=buffer.substring(0,buffer.length()-1);
                mView.showExitDialog(st);
                return false;
            }*/

        }
        return true;
    }

    @Override
    protected void exit() {
        EventBusUtil.unRegister(this);
        super.exit();
    }
}
